import { _decorator, AssetManager, assetManager, Component, Prefab, Node, instantiate, Canvas, find } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('NewComponent')
export class NewComponent extends Component {

    @property(Node)
    wxBtn: any = null;
    canvas: Canvas = null;



    start() {

        var canvasNode = find("Canvas");
        this.canvas = canvasNode.getComponent(Canvas);


        var componentTemp = this;
        this.wxBtn.on(Node.EventType.TOUCH_START, function (event) {
            var toast = componentTemp.IE_GetAsset("Prefabs", "Toast", Prefab)
            toast.then(res => {
                console.log('uiPrefab', uiView)
                console.log('res', res)
                // 挂载数据
                var uiView = instantiate(res);
                componentTemp.canvas.node.addChild(uiView);
            });

        });
    }

    public async IE_GetAsset(bundleName: string, assetPath: string, assetType) {
        var bundle: AssetManager.Bundle = assetManager.getBundle(bundleName);
        if (bundle === null) {
            bundle = await this.IE_LoadBundle(bundleName) as any;
            if (bundle === null) {
                // console.log("bundle load err: " + bundleName);
                return;
            }
        }

        var assetData = bundle.get(assetPath);
        if (assetData) {
            return assetData; // 修改了没有返回资源的bug
        }

        assetData = await this.IE_LoadAssetInBundle(bundle, assetPath, assetType) as any;
        return assetData;
    }

    private async IE_LoadBundle(bundleName: string) {
        return new Promise((resolve, reject) => {
            assetManager.loadBundle(bundleName, (err, bundleData) => {
                if (err) {
                    console.log(err);
                    reject(null);
                    return;
                }
                else {
                    resolve(bundleData);
                    return;
                }
            })
        });
    }

    private async IE_LoadAssetInBundle(bundle: AssetManager.Bundle, assetName: string, assetType) {
        return new Promise((resolve, reject) => {
            bundle.load(assetName, assetType, (err, assetData) => {
                if (err) {
                    reject(err);
                    return;
                }
                else {
                    resolve(assetData);
                }
            });
        });
    }
}


